/**
 * 课程列表页面
 * /packageTeacher/pages/courses/list/index
 */

const Router = require('../../../utils/router')
const Storage = require('../../../utils/storage')
const Logger = require('../../../utils/logger')
const Track = require('../../../utils/track')
const { TeacherService } = require('../../../services/index')

Page({
  data: {
    title: '课程列表',
    loading: false,
    refreshing: false,
    loadingMore: false,
    hasMore: true,
    
    // 筛选条件
    showFilter: false,
    showRegionPicker: false,
    filters: {
      category_id: '',
      categoryName: '全部分类',
      region: [],
      regionText: '全国',
      teacher_id: '',
      teacherName: '全部教师',
      level: '',
      levelText: '难度不限',
      min_price: '',
      max_price: '',
      priceRangeText: '价格不限'
    },
    
    // 分类数据
    categories: [],
    
    // 难度等级
    levels: [
      { id: '', name: '难度不限' },
      { id: 'beginner', name: '初级' },
      { id: 'intermediate', name: '中级' },
      { id: 'advanced', name: '高级' }
    ],
    
    // 价格区间
    priceRanges: [
      { id: '', name: '价格不限', min: '', max: '' },
      { id: '0-100', name: '100元以下', min: 0, max: 100 },
      { id: '100-300', name: '100-300元', min: 100, max: 300 },
      { id: '300-500', name: '300-500元', min: 300, max: 500 },
      { id: '500-1000', name: '500-1000元', min: 500, max: 1000 },
      { id: '1000+', name: '1000元以上', min: 1000, max: '' }
    ],
    
    // 课程列表
    courses: [],
    pagination: {
      page: 1,
      limit: 10,
      total: 0
    }
  },

  async onLoad(options) {
    Logger.info('Page loaded: /packageTeacher/pages/courses/list/index', options)
    Track.trackPageView('/packageTeacher/pages/courses/list/index', options)
    
    // 从参数中获取初始筛选条件
    if (options.category_id) {
      this.setData({
        'filters.category_id': options.category_id
      })
    }
    
    if (options.teacher_id) {
      this.setData({
        'filters.teacher_id': options.teacher_id
      })
    }
    
    // 加载分类数据
    await this.loadCategories()
    
    // 加载课程列表
    this.loadCourses()
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadCourses(true)
  },

  /**
   * 加载分类数据
   */
  async loadCategories() {
    try {
      const categories = await TeacherService.getRootCategories()
      this.setData({
        categories: [{ id: '', name: '全部分类' }, ...categories]
      })
      
      // 更新当前选中分类的名称
      if (this.data.filters.category_id) {
        const currentCategory = categories.find(c => c.id == this.data.filters.category_id)
        if (currentCategory) {
          this.setData({
            'filters.categoryName': currentCategory.name
          })
        }
      }
    } catch (error) {
      Logger.error('Failed to load categories', error)
    }
  },

  /**
   * 加载课程列表
   */
  async loadCourses(refresh = false) {
    if (refresh) {
      this.setData({
        'pagination.page': 1,
        courses: [],
        hasMore: true,
        refreshing: true
      })
    } else {
      this.setData({ loading: true })
    }

    try {
      const { filters, pagination } = this.data
      
      // 构建查询参数
      const params = {
        page: pagination.page,
        limit: pagination.limit,
        category_id: filters.category_id,
        teacher_id: filters.teacher_id,
        level: filters.level,
        min_price: filters.min_price,
        max_price: filters.max_price,
        status: 'active'
      }
      
      // 调用 API 获取课程列表
      const result = await TeacherService.getCourseList(params)
      
      // API 直接返回数组或包含courses字段的对象
      const courses = Array.isArray(result) ? result : (result.courses || result.data || [])
      const total = result.total || courses.length
      
      this.setData({
        courses: refresh ? courses : [...this.data.courses, ...courses],
        hasMore: courses.length >= pagination.limit,
        'pagination.total': total
      })
      
    } catch (error) {
      Logger.error('Failed to load courses', error)
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({
        loading: false,
        refreshing: false,
        loadingMore: false
      })
    }
  },

  /**
   * 显示筛选面板
   */
  onShowFilter() {
    this.setData({ showFilter: true })
  },

  /**
   * 隐藏筛选面板
   */
  onHideFilter() {
    this.setData({ showFilter: false })
  },

  /**
   * 分类选择
   */
  onCategorySelect(e) {
    const { category, name } = e.currentTarget.dataset
    this.setData({
      'filters.category_id': category,
      'filters.categoryName': name
    })
  },

  /**
   * 价格区间选择
   */
  onPriceRangeSelect(e) {
    const { range, name, min, max } = e.currentTarget.dataset
    this.setData({
      'filters.min_price': min || '',
      'filters.max_price': max || '',
      'filters.priceRangeText': name
    })
  },

  /**
   * 难度选择
   */
  onLevelSelect(e) {
    const { level, name } = e.currentTarget.dataset
    this.setData({
      'filters.level': level,
      'filters.levelText': name
    })
  },

  /**
   * 显示地区选择器
   */
  onShowRegionPicker() {
    this.setData({ showRegionPicker: true })
  },

  /**
   * 地区选择确认
   */
  onRegionConfirm(e) {
    const { selectedPath, selectedText } = e.detail
    this.setData({
      'filters.region': selectedPath,
      'filters.regionText': selectedText || '全国',
      showRegionPicker: false
    })
  },

  /**
   * 地区选择取消
   */
  onRegionCancel() {
    this.setData({ showRegionPicker: false })
  },

  /**
   * 应用筛选
   */
  onApplyFilter() {
    this.setData({ showFilter: false })
    this.loadCourses(true)
    
    Track.trackClick('course_filter_apply', 'filter', this.data.filters)
  },

  /**
   * 重置筛选
   */
  onResetFilter() {
    this.setData({
      'filters.category_id': '',
      'filters.categoryName': '全部分类',
      'filters.region': [],
      'filters.regionText': '全国',
      'filters.teacher_id': '',
      'filters.teacherName': '全部教师',
      'filters.level': '',
      'filters.levelText': '难度不限',
      'filters.min_price': '',
      'filters.max_price': '',
      'filters.priceRangeText': '价格不限'
    })
  },

  /**
   * 课程项点击
   */
  onCourseItemTap(e) {
    const { id } = e.currentTarget.dataset
    Track.trackClick('course_item', 'navigation', { course_id: id })
    Router.navigateTo(`/packageTeacher/pages/courses/detail/index?id=${id}`)
  },

  /**
   * 教师点击
   */
  onTeacherTap(e) {
    const { teacherId } = e.currentTarget.dataset
    Track.trackClick('teacher_item', 'navigation', { teacher_id: teacherId })
    Router.navigateTo(`/packageTeacher/pages/detail/index?id=${teacherId}`)
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadCourses(true).finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (!this.data.hasMore || this.data.loadingMore) return
    
    this.setData({
      'pagination.page': this.data.pagination.page + 1,
      loadingMore: true
    })
    
    this.loadCourses()
  }
})
